<template>
  <view class="container">
    <u-navbar :autoBack="true" bg-color="transparent" />
    <!-- 顶部图片 -->
    <view class="tour-image">
      <video
        v-if="hasVideo"
        :src="videoSrc"
        autoplay
        controls
        style="width: 100%; height: 100%; position: relative;"
        :controls-style="videoControlsStyle"
      />
      <image v-else :src="detail.CoverImg" mode="aspectFill"/>
    </view>
    <!-- 中间内容介绍 -->
    <view class="tour-content">
      <view class="tour-title">
        <text>{{ detail.Title }}</text>
      </view>
      <mp-html :content="detail.ChineseSubstance || detail.Substance" lazy-load images-update-mode="onLoad"/>
      <!-- 自定义圆形音频播放器 -->
      <view v-if="hasAudio" class="custom-audio-player">
        <view class="circle-player" @click="togglePlay">
          <view class="circle-progress" :style="circleStyle">
            <view class="inner-circle">
              <view v-if="!isPlaying" class="play-icon">
                <view class="play-triangle"></view>
              </view>
              <view v-else class="pause-icon">
                <view class="pause-line"></view>
                <view class="pause-line"></view>
              </view>
              <view class="audio-time">{{ formatTime(duration - currentTime) }}</view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <!-- 底部按钮 -->
    <view class="bottom-actions">
      <view class="action-row">
        <view class="action-btn share-btn" @click="shareContent">
          <image src="https://wzws.wanshanlundiao.cn/upload/img/20250516/202505161310562107.png" class="btn-icon" />
          <text>分享</text>
          <button open-type="share" class="share-open-btn"></button>
        </view>
        <view class="action-btn" @click="goToDestination">
          <image src="https://wzws.wanshanlundiao.cn/upload/img/20250516/202505161311147684.png" class="btn-icon" />
          <text>前往</text>
        </view>
      </view>
    </view>
    <!-- 语言切换按钮 -->
    <view v-if="showLangBtn" class="lang-switch-btn" @click="switchLanguage">
      {{ currentLangIndex === 0 ? '切换英文' : '切换中文' }}
    </view>
    <!-- 原生音频播放器（隐藏） -->
    <audio v-if="audioSrc" :src="audioSrc" style="display: none;" />
  </view>
</template>

<script>
import {getArticleDetail} from "@/api/homePage";

export default {
  name: 'GuidedTourArticle',
  data() {
    return {
      detail: {},
      showLangBtn: false,
      currentLangIndex: 0,
      hasAudio: false,
      audioSrc: '',
      // 音频播放相关
      audioContext: null,
      isPlaying: false,
      currentTime: 0,
      duration: 0, // 默认0，单位为秒
      circlePercent: 0,
      audioTimer: null,
      hasVideo: false,
      videoSrc: '',
    }
  },
  computed: {
    // 计算圆形进度条的样式
    circleStyle() {
      return `background: conic-gradient(#03a9f4 ${this.circlePercent}%, transparent 0%)`
    },
    videoControlsStyle() {
      return {
        position: 'absolute',
        bottom: '30rpx',
        left: '0',
        right: '0'
      }
    }
  },
  onLoad(options) {
    console.log(options)
    if (options && options.id) {
      getArticleDetail({Id: options.id}).then(res => {
        this.detail = res.Data;
        this.showLangBtn = Array.isArray(res.Data.OtherLanguageInfo) && res.Data.OtherLanguageInfo.length;
        this.currentLangIndex = 0;
        uni.setNavigationBarTitle({
          title: res.Data.Title
        })
        const { VideoFile } = this.detail;
        if (this.isAudioFile(VideoFile)) {
          this.hasAudio = true;
          this.audioSrc = VideoFile;
        } else if (this.isVideoFile(VideoFile)) {
          this.hasVideo = true;
          this.videoSrc = VideoFile;
          this.initWifi();
        }
        if (this.hasAudio) {
          this.$nextTick(() => {
            this.initAudioContext();
          })
        }
      })
    } else {
      // 没有ID时也初始化一个空的音频上下文
      this.$nextTick(() => {
        this.initAudioContext();
      });
    }
  },
  onReady() {
    // 页面就绪后如果存在音频再次确保音频上下文存在
    if (this.hasAudio) {
      this.initAudioContext();
    }
  },
  onUnload() {
    // 页面卸载时释放资源
    if (this.audioContext) {
      this.audioContext.destroy();
      this.audioContext = null;
    }
    if (this.audioTimer) {
      clearInterval(this.audioTimer);
      this.audioTimer = null;
    }
  },
  onShareAppMessage() {
    console.log(123)
    // 分享的标题，使用文章标题或默认标题
    const title = this.detail.Title || '精彩推荐';
    // 分享的图片，使用文章封面图或默认图片
    const imageUrl = this.detail.CoverImg || '';
    // 分享的路径，带上文章ID以便打开时能够加载正确的内容
    const path = `/pages/guidedTourArticle/index?id=${this.detail.Id}`;
    return {
      title: title,
      path: path,
      imageUrl: imageUrl,
      success(res) {
        uni.showToast({
          title: '分享成功',
          icon: 'success'
        });
      },
      fail(err) {
        uni.showToast({
          title: '分享失败',
          icon: 'none'
        });
      }
    };
  },
  methods: {
    isAudioFile(src) {
      const audioList = 'mp3, wav, ogg';
      const audioExtensions = audioList.split(', ').join('|');
      const audioRegex = new RegExp(`\\.(${audioExtensions})$`, 'i');
      return audioRegex.test(src);
    },
    isVideoFile(src) {
      const videoList = 'mp4, mov, avi';
      const videoExtensions = videoList.split(', ').join('|');
      const videoRegex = new RegExp(`\\.(${videoExtensions})$`, 'i');
      return videoRegex.test(src);
    },
    async initWifi() {
      const res = await uni.getNetworkType();
      if (res[1].networkType !== 'wifi') {
        uni.showToast({
          title: '视频可能消耗流量，注意在wifi下观看',
          icon:'none'
        })
      }
    },
    // 格式化时间为 mm:ss
    formatTime(seconds) {
      const min = Math.floor(seconds / 60);
      const sec = Math.floor(seconds % 60);
      return `${min.toString().padStart(2, '0')}:${sec.toString().padStart(2, '0')}`;
    },
    goToDestination() {
      // 从detail中获取经度、纬度和标题
      const longitude = this.detail.Lng || 0;
      const latitude = this.detail.Lat || 0;
      const title = this.detail.Title || '';

      // 跳转到地图页面并传递参数
      uni.navigateTo({
        url: `/guidedTour_subpages/mapLogation?longitude=${longitude}&latitude=${latitude}&title=${title}`
      });
    },
    // 初始化音频上下文
    initAudioContext() {
      // 销毁之前的实例
      if (this.audioContext) {
        this.audioContext.destroy();
        this.audioContext = null;
      }

      // 创建新的音频实例，即使没有音频源也创建
      this.audioContext = uni.createInnerAudioContext();

      // 设置音频源（如果有）
      if (this.audioSrc) {
        this.audioContext.src = this.audioSrc;
      }

      this.audioContext.autoplay = false;

      console.log('初始化音频上下文', this.audioContext, '音频源:', this.audioContext.src);

      // 监听音频加载完成事件
      this.audioContext.onCanplay(() => {
        console.log('音频可以播放');
      });

      // 监听音频播放进度更新事件
      this.audioContext.onTimeUpdate(() => {
        this.currentTime = this.audioContext.currentTime;
        this.duration = this.audioContext.duration || 325; // 如果获取不到时长，使用默认值
        this.circlePercent = (this.currentTime / this.duration) * 100;
      });

      // 监听音频播放结束事件
      this.audioContext.onEnded(() => {
        this.isPlaying = false;
        this.currentTime = 0;
        this.circlePercent = 0;
        clearInterval(this.audioTimer);
      });

      // 监听音频播放错误事件
      this.audioContext.onError((res) => {
        console.error('音频播放错误:', res);
        uni.showToast({
          title: '音频播放失败',
          icon: 'none'
        });
        this.isPlaying = false;
      });
    },
    // 播放/暂停音频
    togglePlay() {
      console.log('当前音频上下文:', this.audioContext);

      // 如果没有音频上下文，尝试初始化
      if (!this.audioContext) {
        console.log('音频上下文不存在，正在初始化...');
        this.initAudioContext();

        // 如果仍然没有音频上下文或没有音频源，显示提示并返回
        if (!this.audioContext || !this.audioSrc) {
          uni.showToast({
            title: '没有可用的音频',
            icon: 'none'
          });
          return;
        }
      }

      // 检查是否有音频源
      if (!this.audioContext.src) {
        console.log('没有设置音频源，正在尝试设置...');
        const audioSrc = this.currentLangIndex === 0
            ? (this.detail.VideoFile || "")
            : (this.detail.AudioFile || "");

        if (audioSrc) {
          this.audioContext.src = audioSrc;
          this.audioSrc = audioSrc;
        } else {
          uni.showToast({
            title: '没有可用的音频',
            icon: 'none'
          });
          return;
        }
      }

      if (this.isPlaying) {
        console.log('暂停播放');
        this.audioContext.pause();
        this.isPlaying = false;
        clearInterval(this.audioTimer);
      } else {
        console.log('开始播放');
        this.audioContext.play();
        this.isPlaying = true;

        // 使用定时器更新进度，避免依赖onTimeUpdate事件不稳定的问题
        if (this.audioTimer) clearInterval(this.audioTimer);
        this.audioTimer = setInterval(() => {
          if (this.audioContext) {
            this.currentTime = this.audioContext.currentTime;
            this.duration = this.audioContext.duration || 325;
            this.circlePercent = (this.currentTime / this.duration) * 100;
          }
        }, 500);
      }
    },
    // 停止音频播放
    stopAudio() {
      if (this.audioContext) {
        this.audioContext.stop();
        this.isPlaying = false;
        this.currentTime = 0;
        this.circlePercent = 0;
        clearInterval(this.audioTimer);
      }
    },
    switchLanguage() {
      if (!this.showLangBtn) return;
      if (this.currentLangIndex === 0) {
        this.detail = this.detail.OtherLanguageInfo[0];
        this.currentLangIndex = 1;
        uni.setNavigationBarTitle({
          title: this.detail.Title
        })
      } else {
        getArticleDetail({Id: this.detail.ArticleId || this.detail.Id}).then(res => {
          this.detail = res.Data;
          this.currentLangIndex = 0;
          uni.setNavigationBarTitle({
            title: res.Data.Title
          })
        })
      }
      if (this.hasAudio) {
        this.audioSrc = this.currentLangIndex === 0 ? (this.detail.VideoFile || "") : (this.detail.AudioFile || "");
        // 重新初始化音频
        this.stopAudio();
        this.$nextTick(() => {
          this.initAudioContext();
        });
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background-color: #F5F6F7;
  position: relative;
  display: flex;
  flex-direction: column;
  .tour-image {
    position: relative;
    width: 100%;
    height: 400rpx;
    image {
      width: 100%;
      height: 100%;
    }
    video {
      width: 100%;
      height: 100%;
    }
  }
  .tour-content {
    flex: 1;
    padding: 30rpx;
    background-color: #fff;
    border-radius: 30rpx 30rpx 0 0;
    margin-top: -30rpx;
    position: relative;
    z-index: 1;
    .tour-title {
      margin-bottom: 25rpx;
      font-size: 44rpx;
      font-weight: bold;
      color: #333;
    }
    /* 自定义圆形音频播放器样式 */
    .custom-audio-player {
      position: absolute;
      top: 0;
      right: 30rpx;
      display: flex;
      justify-content: center;
      transform: translateY(-50%);
      z-index: 10;
      .circle-player {
        position: relative;
        width: 200rpx;
        height: 200rpx;
        border-radius: 50%;
        cursor: pointer;
        box-shadow: 0 8rpx 20rpx rgba(0, 0, 0, 0.1);
        .circle-progress {
          width: 100%;
          height: 100%;
          border-radius: 50%;
          display: flex;
          justify-content: center;
          align-items: center;
          background: conic-gradient(#03a9f4 0%, transparent 0%);
          transition: background 0.3s;
          .inner-circle {
            width: 180rpx;
            height: 180rpx;
            border-radius: 50%;
            background: white;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            .play-icon {
              margin-bottom: 10rpx;
              .play-triangle {
                width: 0;
                height: 0;
                border-style: solid;
                border-width: 20rpx 0 20rpx 34rpx;
                border-color: transparent transparent transparent #03a9f4;
              }
            }
            .pause-icon {
              display: flex;
              margin-bottom: 10rpx;
              .pause-line {
                width: 12rpx;
                height: 40rpx;
                background-color: #03a9f4;
                margin: 0 6rpx;
                border-radius: 2rpx;
              }
            }
            .audio-time {
              font-size: 32rpx;
              color: #666;
              font-weight: 500;
            }
          }
        }
      }
    }
  }
  .bottom-actions {
    padding: 20rpx 30rpx;
    background-color: #fff;
    box-shadow: 0 -4rpx 10rpx rgba(0, 0, 0, 0.05);
    .action-row {
      display: flex;
      justify-content: space-between;
      align-items: center;
      gap: 20rpx;
      .action-btn {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 48%;
        height: 90rpx;
        border-radius: 50rpx;
        padding: 15rpx 0;
        position: relative;
        .share-open-btn{
          position: absolute;
          width: 100%;
          height: 100%;
          top: 0;
          left: 0;
          opacity: 0;
        }
        .btn-icon {
          width: 34rpx;
          height: 34rpx;
          margin-right: 12rpx;
        } 
        text {
          font-size: 28rpx;
        }
      }
      .share-btn {
        background-color: #fff;
        border: 1px solid #eee;
        text {
          color: #333;
        }
      }
    }
  }
  .lang-switch-btn {
    position: fixed;
    right: 40rpx;
    bottom: 180rpx;
    z-index: 999;
    background: #007aff;
    color: #fff;
    padding: 20rpx 30rpx;
    border-radius: 50rpx;
    font-size: 28rpx;
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.12);
  }
}
</style>